import React, { PureComponent } from 'react'
import { StyleSheet, View, Text } from 'react-native'
import PropTypes from 'prop-types'
import MessageItem from 'src/components/message/MessageItem'
import { notifyIcon } from 'src/utils/ConfigUtil'
import EmptyView from 'src/components/empty-view'
import CustomFlatList from 'src/components/custom-flat-list'
import { DismissLoading, ShowLoading } from 'src/utils/ToastUtil'
import { getMessageList, updateMessageList } from 'src/utils/RequestAPI'
import RefreshState from 'src/components/custom-flat-list/RefreshState'
import NavigationUtil from 'src/utils/NavigationUtil'
import { ScaleS, ScaleT, WIDTH } from 'src/utils/ScreenUtil'
import CustomImage from 'src/components/image/CustomImage'
import CustomButton from 'src/components/button/CustomButton'

const COMPANY = require('@/imgC/message/notify_icon_3.png')
const MEMBER = require('@/imgC/message/notify_icon_2.png')
const POSITION = require('@/imgC/message/notify_icon_1.png')
const FAMOUS = require('@/imgC/message/notify_icon_5.png')

export default class NotifyComponent extends PureComponent {
  static propTypes = {
    userId: PropTypes.number,
    navigation: PropTypes.object,
    role: PropTypes.string,
    readNotify: PropTypes.func
  }

  constructor (props) {
    super(props)
    if (this.componentWillFocus) {
      this.componentWillFocus = this.componentWillFocus.bind(this)
      this.willFocusSubscription = props.navigation.addListener(
        'willFocus',
        this.componentWillFocus
      )
    }
    this.state = {
      notifyArr: [],
      fHeight: 0
    }
    this.currentPage = 1
  }

  render () {
    const { notifyArr } = this.state
    return (
      <CustomFlatList
        style={styles.container}
        ref={this._cflr}
        onLayout={this._onLayout}
        data={notifyArr}
        renderItem={this._renderItem}
        keyExtractor={this._keyExtractor}
        bounces={!!(notifyArr && notifyArr.length > 0)}
        ListEmptyComponent={this._listEmptyComponent()}
        onHeaderRefresh={this._onHeaderRefresh}
        onFooterRefresh={this._onFooterRefresh}
      />
    )
  }

  _onLayout = (e) => {
    const height = e.nativeEvent.layout.height
    if (this.state.fHeight < height) {
      this.setState({
        fHeight: height
      })
    }
  }

  _cflr = (ref) => {
    this.customFlatListRef = ref
  }

  _keyExtractor = (item, index) => {
    return item.id.toString()
  }

  componentDidMount () {
    this.currentPage = 1
    this.getUnReadCount()
  }

  componentWillFocus () {
    this.currentPage = 1
    this.getUnReadCount()
  }

  getUnReadCount = () => {
    this._getMessageList(true).then((data) => {
      const ids = []
      // isRead : 1 :未读 0 : 已读 --int
      data.map(item => {
        item.isRead && ids.push(item.id)
      })
      // ids.length && updateMessageList({ ids: ids.join(',') })
      this.props.readNotify(ids)
    })
  }

  /**
   * 获取通知列表
   * @param showLoading
   * @private
   */
  _getMessageList = (showLoading, type) => {
    return new Promise(resolve => {
      const { userId, role } = this.props
      if (!userId) return
      showLoading && ShowLoading()
      getMessageList({
        params: {
          page: this.currentPage,
          limit: 10,
          userId,
          type: role
        }
      }).then((data) => {
        const { notifyArr } = this.state
        showLoading && DismissLoading()
        switch (type) {
          case 'REFRESH':
            this.setState({ notifyArr: data.data })
            break
          case 'LOADMORE':
            this.setState({ notifyArr: [...notifyArr, ...data.data] })
            break
          default:
            this.setState({ notifyArr: data.data })
            break
        }
        this._setEndRefreshing(data.data)
        resolve(data.data)
      }).catch(() => {
        showLoading && DismissLoading()
        this.currentPage--
        this.customFlatListRef.endRefreshing(RefreshState.Failure)
        resolve()
      })
    })
  }

  _setEndRefreshing = (data) => {
    if (data.length < 10) {
      this.customFlatListRef.endRefreshing(RefreshState.NoMoreData)
    } else {
      this.customFlatListRef.endRefreshing(RefreshState.CanLoadMore)
    }
  }

  /**
   * 下拉刷新
   * @private
   */
  _onHeaderRefresh = () => {
    this.currentPage = 1
    this._getMessageList(false, 'REFRESH')
  }

  /**
   * 上拉加载
   * @private
   */
  _onFooterRefresh = () => {
    this.currentPage++
    this._getMessageList(false, 'LOADMORE')
  }

  _listEmptyComponent = () => {
    const { userId } = this.props
    const { fHeight } = this.state
    return (
      // <EmptyView
      //   emptyImg={require('src/imgC/message/message_null.png')}
      //   firstTip={userId ? '还没有通知哦～' : '登录后才可看通知哦～'}
      //   onPress={this._goLogin}
      //   btnLabel={userId ? null : '登录'}/>
      <View style={{ height: fHeight }}>
        <View style={styles.emptyView}>
          <CustomImage style={styles.emptyImg} source={userId ? require('src/imgC/message/default_message.png') : require('src/imgC/message/default_empty.png')}/>
          <CustomButton style={styles.btnView} onPress={this._goLogin}>
            {!userId && <Text style={styles.btnLabel}>登录</Text>}
          </CustomButton>
        </View>
      </View>
    )
  }

  _goLogin = () => {
    NavigationUtil.navigate('OneLogin')
  }

  _renderItem = ({ item }) => {
    const newItem = {
      id: item.id,
      nick: item.title,
      lastMsg: item.message,
      msgTime: item.gmtModify,
      avatarUrl: this._getMessageListUrl(item.messageType),
      unread: item.isRead,
      messageType: item.messageType
    }
    const errorSource = this._getErrorSource(item.type)
    return (
      <MessageItem item={newItem} errorSource={errorSource} needFormatTime={true} messageType='notify'/>
    )
  }

  _getErrorSource = (type) => {
    switch (parseInt(type)) {
      case 1:// 企业申请通知
      case 2:// 企业申请通过
      case 3:// 企业申请未通过
      case 17:// 企业拉黑
        return notifyIcon.companyIcon
      case 4:// 会员开通
      case 5:// 会员到期
      case 6:// 会员过期
        return notifyIcon.memberIcon
      case 7:// 名企申请通知
      case 8:// 名企申请通过
      case 9:// 名企申请未通过
        return notifyIcon.famousCompanyIcon
      case 10:// 职位发布
      case 11:// 职位下架
      case 12:// 平台下架
      case 13:// 岗位上架审核
      case 14:// 岗位上架通过
      case 15:// 岗位上架未通过
      case 16:// 永久下架
        return notifyIcon.positionIcon
    }
  }

  // 获取头像
  _getMessageListUrl = (type) => {
    let url = ''
    if (type && type.split('_')) {
      switch (type.split('_')[0]) {
        case 'COMPANY':
          url = COMPANY
          break
        case 'MEMBER':
          url = MEMBER
          break
        case 'POSITION':
        case 'POST':
        case 'PLATFORM':
        case 'PERMANENT':
        case 'JOB':
          url = POSITION
          break
        case 'FAMOUS':
          url = FAMOUS
          break
      }
    }
    return url
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white'
  },
  emptyView: {
    flex: 1,
    position: 'absolute',
    bottom: 0
  },
  emptyImg: {
    width: WIDTH,
    height: ScaleS(342)
  },
  btnView: {
    position: 'absolute',
    left: ScaleS(81),
    top: ScaleS(150),
    borderRadius: ScaleS(4),
    backgroundColor: '#FFE400',
    paddingHorizontal: ScaleS(22),
    paddingVertical: ScaleS(8),
    justifyContent: 'center',
    alignItems: 'center'
  },
  btnLabel: {
    fontSize: ScaleT(12),
    fontWeight: '500',
    color: '#3C3C3C'
  }
})
